package com.honey.mybatis.generator.dao.method;

import java.util.List;

import com.honey.compilation.java.AbstractJavaCompilation;
import com.honey.compilation.java.IfBlock;
import com.honey.compilation.java.JavaKeyWord;
import com.honey.compilation.java.Method;
import com.honey.compilation.java.Parameter;
import com.honey.core.dbmapping.introspect.IntrospectSchema;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.types.FullyQualifiedJavaType;
import com.honey.core.types.JDKFullyQualifiedJavaType;
import com.honey.core.utils.EmptyUtility;
import com.honey.core.utils.StringUtility;
import com.honey.mybatis.generator.MybatisPlugin;
import com.honey.mybatis.generator.dao.DaoConstant;

/**
 * 按照primaryKey查询
 * @author Administrator
 *
 */
public class DeleteByPrimaryKeyMethod extends AbstractCreateInterfaceMethod{
	
	private static final String METHOD_NAME="deleteByPrimaryKey";
	

	private static final FullyQualifiedJavaType UPDATE_TYPE = new FullyQualifiedJavaType("E");
	
	private static final FullyQualifiedJavaType RETURN_TYPE = JDKFullyQualifiedJavaType.getIntInstance();
	
	private boolean isUseSession = false ;
	
	boolean enable = false ;
	public DeleteByPrimaryKeyMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn
			) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
		isEnable();
	}
	
	public DeleteByPrimaryKeyMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn,
			boolean  isUseSession
			) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
		this.isUseSession = isUseSession;
		
		isEnable();
		
	}
	
	private void isEnable(){
		if( mybatisPlugin.isEnableVirtualDeleteKey()){
			for(Column column : introspectSchemaColumn.allColumns() ){
				String value = ((TableColumn)column).getVirtualDeleteValue();
				if( StringUtility.stringHasValue(value)){
					enable = true;
					break;
				}
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#addBody(com.honey.compilation.java.Method)
	 */
	@Override
	protected void addBody(Method method) {	
		if( enable ){
			Parameter par = new Parameter(JDKFullyQualifiedJavaType.getBoolInstance(),"isPhysicDel" );
			par.addJavaDocLine("是否物理删除 true:是 false:虚拟删除");
			method.addParameter(par);
			method.addJavaDocLine("启用的虚拟删除功能,默认使用虚拟删除. ");
		}
		IfBlock ifBlock = null;
		if( isUseSession()){
			ifBlock = new IfBlock(new StringBuilder().append( DaoConstant.SQL_SESSION_NAME ).append(" == null").toString());
			ifBlock.addBodyLine("return -1");
			method.addBlocks(ifBlock);
		}
		
		List<TableColumn> columns = ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns();
		if( columns.size() == 1){
			method.addBodyLine(
					new StringBuilder( )
					.append(JavaKeyWord.RETURN)
					//.append("super.")
					.append(mybatisPlugin.getDependentModel().call(null))
					.append("delete( ")
					.append( isUseSession()?DaoConstant.SQL_SESSION_NAME+" , ":"" )
					//.append(DaoConstant.DELETE_BY_PRIMARYKEY_FIELD_NAME)
					//.append(super.getMapperId().getDeleteByPrimaryKeyMapperId())
					.append( (enable ? " isPhysicDel ? ":"") + super.getMapperId().getDeleteByPrimaryKeyMapperId()+ (enable ? (" : "+ super.getMapperId().getVirtualDeleteByPrimaryKeyMapperId()):"" ))
					.append(" , ")
					.append(columns.get(0).getJavaProperty())
					.append(" )")
					.toString()
			);
		}else if( columns.size() > 1){
			method.addBodyLine("Map<String, Object> parameter = new HashMap<String, Object>();");
			for( TableColumn tc : columns ){
				method.addBodyLine("parameter.put(\""+tc.getJavaProperty()+"\","+tc.getJavaProperty()+")");
			}
			method.addBodyLine(
					new StringBuilder( )
					.append(JavaKeyWord.RETURN)
					.append(mybatisPlugin.getDependentModel().call(null))
					.append("delete( ")
					.append( isUseSession()?DaoConstant.SQL_SESSION_NAME+" , ":"" )
					//.append(DaoConstant.DELETE_BY_PRIMARYKEY_FIELD_NAME)
					.append(super.getMapperId().getDeleteByPrimaryKeyMapperId())
					.append(" , parameter )")
					.toString()
			);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getMethodName()
	 */
	@Override
	protected String getMethodName() {		
		String answer = null;
		if( mybatisPlugin.isEnableDelete() ){
			if( !isUseSession ){
				answer = METHOD_NAME;
			}else if( isUseSession  && mybatisPlugin.isEnableUseSqlSession() ){
				answer = METHOD_NAME;
			}
		}
		return answer;
	}
	
	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.dao.method.AbstractCreateInterfaceMethod#getUpdateEntityType()
	 */
	@Override
	public FullyQualifiedJavaType getUpdateEntityType() {
		
		return UPDATE_TYPE;
	}

	/**
	 * @return the isUseSession
	 */
	@Override
	public final boolean isUseSession() {
		return isUseSession;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getJavaDoc()
	 */
	@Override
	protected String[] getJavaDoc() {
		String[] answer = new String[]{
			" 按照主键删除。"
		};
		return answer;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getReturnType()
	 */
	@Override
	protected FullyQualifiedJavaType getReturnType() {
		
		return RETURN_TYPE;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.dao.method.AbstractCreateInterfaceMethod#isCondition()
	 */
	@Override
	public boolean isCondition() {
		
		return false;
	}
	
	protected Parameter[] getParameter() {
		List<TableColumn> primaryKeyColumns = ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns() ;
		int size = 1;
		if( ! EmptyUtility.isListEmpty(primaryKeyColumns)){
			size +=primaryKeyColumns.size();
		}
		
		Parameter[] answer = new Parameter[size];
		Parameter parameter = null;
		if( isUseSession()){
			parameter = new Parameter(DaoConstant.SQL_SESSION_PACKAGE,DaoConstant.SQL_SESSION_NAME);
			parameter.addJavaDocLine("外部传入SqlSession");
			answer[0] = parameter;
		}
		TableColumn tc = null;
		for( int i=0 , length = primaryKeyColumns.size();i < length ; i++ ){
			tc = primaryKeyColumns.get(i); 
			parameter = new Parameter(tc.getFullyQualifiedJavaType(),tc.getJavaProperty());
			setBaseType(parameter);
			parameter.addJavaDocLine(tc.getComment());
			answer[i+1] = parameter;
		}
		return answer ;
	}
}
